package com.billsystem.interceptor;

import com.billsystem.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取当前请求的会话对象 HttpSession，
        HttpSession session = request.getSession();
        //获取应用的上下文路径。
        String contextPath=session.getServletContext().getContextPath();
        //定义一个字符串数组 requireAuthPages，其中包含需要进行登录验证的页面名称，index是核心页面
        String[] requireAuthPages = new String[]{
                "index"
        };
        //获取当前请求的 URI
        String uri = request.getRequestURI();
        //并去除上下文路径
        uri = StringUtils.remove(uri, contextPath+"/");
        //得到实际的页面名称
        String page = uri;

        //调用 beginsWith 方法检查当前页面是否在需要验证的页面列表中
        if(beginsWith(page, requireAuthPages)){

            if(session.getAttribute("userId") != null){
                return true;
            }else{
                response.sendRedirect("/login");
            }
        }
        return true;
    }
    //获取url中的id
    private int getLastUrlId(String uri){
        char[] cs = uri.toCharArray();
        int id = 0;
        for(int i = 5; i < cs.length; i++){
            if(Character.isDigit(cs[i])){
                id += id * 10 + (cs[i] - '0');
            }else{
                break;
            }
        }
        return id;
    }
    //检查page是否以requiredAuthPages中的任意一个字符串开头
    private boolean beginsWith(String page, String[] requiredAuthPages) {
        boolean result = false;
        for (String requiredAuthPage : requiredAuthPages) {
            if(StringUtils.startsWith(page, requiredAuthPage)) {
                result = true;
                break;
            }
        }
        return result;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
